package edu.gyc.mysystem.service.impl;

import edu.gyc.mysystem.dao.UserRoleMapper;
import edu.gyc.mysystem.service.UserRoleService;
import edu.gyc.mysystem.vo.UserRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    UserRoleMapper userRoleMapper;
    @Override
    public Set<UserRoleVo> getUserRoles() {
        List<UserRoleVo> userRoles=userRoleMapper.getUserRoles();
        log.info("userRoles的长度："+userRoles.size());
        Set<UserRoleVo> userRoleVoSet = new LinkedHashSet<>();
        //一个用户可以有多个角色，利用Set集合去除userRoles重复的用户名，需要覆盖UserRoleVo对象的equal和hashcode方法
        for (UserRoleVo ur : userRoles) {
            userRoleVoSet.add(ur);
        }
        log.info("userRoleSet的长度："+userRoleVoSet.size());

        for (UserRoleVo userRoleVo : userRoleVoSet) {
            if (userRoleVo.getDescription() != null) {//用户可能没有分配角色
                userRoleVo.getRoleSet().add(userRoleVo.getDescription());
            }
           //遍历userRoles，给UserRoleVo对象的roleSet赋值
            for (UserRoleVo t : userRoles) {
                if (userRoleVo.getUsername().equals(t.getUsername())) {
                    if (userRoleVo.getDescription() != null) {
                        if(!userRoleVo.getDescription().equals(t.getDescription())){

                            userRoleVo.getRoleSet().add(t.getDescription());
                        }
                    }

                }
            }

            userRoleVo.setRolenames(userRoleVo.getRoleSet().toString());

        }
        return userRoleVoSet;
    }
}
